import Taro, { IToastIcon } from '@tarojs/taro'
import { obj2query } from '@/utils'

/**
 * 分发页面hook使非页面组件能够响应相关生命周期
 * 示例: @/components/FixedBottom注意在destroyed中移除相关事件,否则监听方法会重复注册触发
 */
export default {
  onReady() {
    Taro.eventCenter.trigger('onReady')
  },
  onUnload() {
    Taro.eventCenter.trigger('onUnload')
  },
  methods: {
    toPage(url: string, params = {}) {
      let query = ''
      if (params) {
        query = obj2query(params)
      }
      Taro.navigateTo({
        url: url + '?' + query
      })
    },
    showMsg(title: string, icon: IToastIcon = 'none') {
      Taro.showToast({
        title,
        icon
      })
    },
    back() {
      Taro.navigateBack()
    },
    detailBack(data: Record<string, unknown>) {
      const pages = Taro.getCurrentPages()
      const page = pages[pages.length - 2]
      page.onShow(data)
      Taro.navigateBack()
    }
  }
}
